import api from "../api/index.js";

export default {
  /**
   * 获取地理位置（异步）
   * @returns {Promise<{latitude: number, longitude: number}>}
   */
  async getLocation() {
    // 先尝试从缓存读取
    const cachedLocation = wx.getStorageSync('location');
    
    if (cachedLocation && cachedLocation.latitude) {
      return cachedLocation;
    }
    // 缓存没有，调用微信 API 获取
    try {
      const res = await new Promise((resolve, reject) => {
        wx.getLocation({
          type: 'gcj02',
          success: resolve,
          fail: reject,
        });
      });
      
      const location = {
        latitude: res.latitude,
        longitude: res.longitude,
      };

      // 存入缓存
      wx.setStorageSync('location', location);
      return location;
    } catch (err) {
      console.error('获取地理位置失败:', err);
      throw err; // 可以选择抛出错误或返回默认值
    }
  },

  /**
   * 获取门店列表（异步）
   * @returns {Promise<Array>}
   */
  async getCompanyList() {
    try {
      // 先尝试从缓存读取
      const cachedCompanyList = wx.getStorageSync('companyList');
      if (cachedCompanyList) {
        return cachedCompanyList;
      }

      // 缓存没有，调用 API 获取
      const location = await this.getLocation(); // 等待获取位置
      const res = await api.getCompanyList({
        data: location
      });

      // 存入缓存
      wx.setStorageSync('companyList', res.data);
      return res.data;
    } catch (err) {
      console.error('获取门店列表失败:', err);
      return []; // 返回空数组，避免页面报错
    }
  },
  refreshMemberCard(){
    let memberCard = wx.getStorageSync('memberCard');
    if (memberCard.id) {
      api.memberCardInfo({
        method: "GET",
        id:memberCard.id
      }).then((res)=>{
        wx.setStorageSync('memberCard',res.data);
      })
    }
  },
  refreshUser(){
    let user = wx.getStorageSync('user');
    if (user.id) {
      api.userInfo({
        method: "GET",
        id:user.id
      }).then((res)=>{
        wx.setStorageSync('user',res.data);
      })
    }
  }
};